﻿namespace ChinaUnicom.Tasks
{
    using Avatar.Schedule;
    using System;
    using System.Windows;
    using System.Net;

    public class CreateSessionTask : ITask
    {
        public CreateSessionTask()
        {
        }

        public void Start()
        {
            if (Started != null)
            {
                Started(this, EventArgs.Empty);
            }

            Factory.Operation.CreateSession(s =>
            {
                try
                {
                    if (s.Status == WebExceptionStatus.Success)
                    {
                        if (Completed != null)
                        {
                            Completed(this, EventArgs.Empty);
                        }
                    }
                    else if (s.Exception != null && Failed != null)
                    {
                        Failed(this, new FailedEventArgs(this, s.Exception));
                    }
                    else if (Failed != null)
                    {
                        Failed(this, new FailedEventArgs(this, new Exception(Factory.Parser.Failed(s.Result))));
                    }
                }
                catch (Exception ex)
                {
                    if (Failed != null)
                    {
                        Failed(this, new FailedEventArgs(this, ex));
                    }
                }
            });
        }

        public event EventHandler Completed;

        public event EventHandler Started;

        public event EventHandler<FailedEventArgs> Failed;

        public int Delay { get { return 50; } }

        public bool IsUnique { get { return true; } }
    }
}
